package net.caixiaomi.info.ui.details;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.AccountDetailsAdapter;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.interfaces.ComonFragmentImpl;
import net.caixiaomi.info.model.AccountDetailItem;
import net.caixiaomi.info.model.AccountDetailListInfo;
import net.caixiaomi.info.model.AccountDetailsModel;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.CountMoneyCurrentMonthModel;
import net.caixiaomi.info.model.CustomerModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.withdraw.WithdrawDetailActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import icepick.State;
import retrofit2.Call;

/**
 * 账户明细
 */

public class AccountDetailsFragment extends BaseFragment implements ComonFragmentImpl, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener, OnRefreshListener {

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;
    @BindView(android.R.id.list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @State
    int mType;
    @State
    int mTimeType = 2;

    private int mPageNum = 1;
    private AccountDetailsAdapter mAdapter;

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_common_list;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mTimeType = getArguments().getInt("timeType", 2);
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mPageNum = 1;
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new AccountDetailsAdapter(R.layout.item_account_detail);
        mAdapter.setOnLoadMoreListener(this, mListView);
        mAdapter.setOnItemClickListener(this);
        TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.empty, null);
        textView.setText(R.string.C_NO_ACCOUNT_DETAIL_DATA);
        mAdapter.setEmptyView(textView);
        mListView.setAdapter(mAdapter);
        mAdapter.setEnableLoadMore(true);
        loadData();
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("pageNum", mPageNum);
        params.put("pageSize", Constants.PAGE_SIZE);
        params.put("amountType", mType);
        params.put("timeType", mTimeType);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<AccountDetailsModel>> getOrderInfoList = requestService.getUserAccountListAndCountTotalUsing(params);
        getOrderInfoList.enqueue(new ResponseCallback<BaseCallModel<AccountDetailsModel>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<AccountDetailsModel> data) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                AccountDetailsModel model = data.data;
                if (model != null) {
                    AccountDetailListInfo pageInfo = model.getPageInfo();
                    List<AccountDetailItem> list = pageInfo.getList();
                    if (mPageNum == 1) {
                        mAdapter.setNewData(list);
                    } else {
                        mAdapter.addData(list);
                        mAdapter.loadMoreComplete();
                    }
                    boolean hasNextPage = Boolean.valueOf(pageInfo.getHasNextPage());
                    mAdapter.setEnableLoadMore(hasNextPage);
                    mAdapter.notifyDataSetChanged();

                    CountMoneyCurrentMonthModel userAccountByTimeDTO = model.getUserAccountByTimeDTO();
                    if (userAccountByTimeDTO != null && mPageNum == 1) {
                        String s = JSON.toJSONString(userAccountByTimeDTO);
                        EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_ACCOUNT_UPDATE_PRICE, s));
                    }
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
            }
        });
    }

    @Override
    public void setType(int type) {
        mType = type;
    }

    @Override
    public void setFilter(String filter) {
        if (!TextUtils.isEmpty(filter)) {
            mTimeType = Integer.valueOf(filter);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        loadData();
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            AccountDetailItem accountDetailItem = mAdapter.getData().get(position);
            if (TextUtils.equals(accountDetailItem.getProcessType(), "4")) {
                Intent intent = new Intent(getActivity(), WithdrawDetailActivity.class);
                intent.putExtra("data", accountDetailItem.getPayId());
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_ACCOUNT_REFRESH:
                    handlePost(event.getMessage());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlePost(String message) {
        try {
            try {
                List<CustomerModel> filter = JSON.parseObject(message, new TypeToken<List<CustomerModel>>() {
                }.getType());
                for (CustomerModel item : filter) {
                    if (item.isSelected()) {
                        mTimeType = item.getId();
                        break;
                    }
                }
                mProgress.setVisibility(View.VISIBLE);
                onRefresh();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onRefresh() {
        mPageNum = 1;
        loadData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        onRefresh();
    }
}
